package memory_store

import (
	"errors"
	"github.com/patrickmn/go-cache"
)

var errTypeAssertionFailed = errors.New("type assertion failed: could not convert interface{} to []byte")

type MemoryStore struct {
	cache *cache.Cache
}

func New() *MemoryStore {
	return &MemoryStore{
		cache.New(cache.DefaultExpiration, cache.NoExpiration),
	}
}

func (m *MemoryStore) Find(token string) (b []byte, exists bool, err error) {
	v, exists := m.cache.Get(token)
	if exists == false {
		return nil, exists, nil
	}

	b, ok := v.([]byte)
	if ok == false {
		return nil, exists, errTypeAssertionFailed
	}

	return b, exists, nil
}

func (m *MemoryStore) Save(token string, b []byte) error {
	m.cache.Set(token, b, cache.NoExpiration)
	return nil
}

func (m *MemoryStore) Delete(token string) error {
	m.cache.Delete(token)
	return nil
}
